package com.example.crm.controller.api;

import com.example.crm.vo.Result;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * 详细数据分析API控制器
 */
@RestController
@RequestMapping("/api/data-analytics")
public class DataAnalyticsAPIController {

    /**
     * 获取客户分析数据
     */
    @GetMapping("/customer")
    public Result<Map<String, Object>> customerAnalytics(
            @RequestParam(required = false) String timeRange,
            @RequestParam(required = false) String segment,
            @RequestParam(required = false) String dimension) {
        
        // 这里应该是调用相关服务层进行实际数据分析
        // 此处为模拟数据
        Map<String, Object> data = new HashMap<>();
        
        // 客户分布数据
        Map<String, Integer> distribution = new HashMap<>();
        distribution.put("新客户", 120);
        distribution.put("潜在客户", 250);
        distribution.put("活跃客户", 430);
        distribution.put("流失客户", 85);
        data.put("distribution", distribution);
        
        // 客户价值分析
        List<Map<String, Object>> valueAnalysis = new ArrayList<>();
        Map<String, Object> highValue = new HashMap<>();
        highValue.put("segment", "高价值");
        highValue.put("count", 120);
        highValue.put("revenue", 1200000);
        highValue.put("retention", 0.92);
        valueAnalysis.add(highValue);
        
        Map<String, Object> mediumValue = new HashMap<>();
        mediumValue.put("segment", "中等价值");
        mediumValue.put("count", 350);
        mediumValue.put("revenue", 850000);
        mediumValue.put("retention", 0.78);
        valueAnalysis.add(mediumValue);
        
        Map<String, Object> lowValue = new HashMap<>();
        lowValue.put("segment", "低价值");
        lowValue.put("count", 430);
        lowValue.put("revenue", 320000);
        lowValue.put("retention", 0.45);
        valueAnalysis.add(lowValue);
        
        data.put("valueAnalysis", valueAnalysis);
        
        // 客户行为分析
        Map<String, Object> behavior = new HashMap<>();
        behavior.put("averageOrderValue", 2500);
        behavior.put("purchaseFrequency", 3.2);
        behavior.put("lastPurchaseAvgDays", 45);
        behavior.put("crossSellRate", 0.28);
        behavior.put("upsellRate", 0.15);
        data.put("behavior", behavior);
        
        return Result.success(data);
    }
    
    /**
     * 获取销售分析数据
     */
    @GetMapping("/sales")
    public Result<Map<String, Object>> salesAnalytics(
            @RequestParam(required = false) String timeRange,
            @RequestParam(required = false) Long teamId,
            @RequestParam(required = false) String dimension) {
        
        // 此处为模拟数据
        Map<String, Object> data = new HashMap<>();
        
        // 销售漏斗数据
        List<Map<String, Object>> funnel = new ArrayList<>();
        Map<String, Object> lead = new HashMap<>();
        lead.put("stage", "线索");
        lead.put("count", 1200);
        lead.put("value", 4800000);
        lead.put("conversionRate", 0.42);
        funnel.add(lead);
        
        Map<String, Object> qualified = new HashMap<>();
        qualified.put("stage", "合格");
        qualified.put("count", 504);
        qualified.put("value", 2520000);
        qualified.put("conversionRate", 0.65);
        funnel.add(qualified);
        
        Map<String, Object> proposal = new HashMap<>();
        proposal.put("stage", "方案");
        proposal.put("count", 328);
        proposal.put("value", 1640000);
        proposal.put("conversionRate", 0.70);
        funnel.add(proposal);
        
        Map<String, Object> negotiation = new HashMap<>();
        negotiation.put("stage", "谈判");
        negotiation.put("count", 230);
        negotiation.put("value", 1150000);
        negotiation.put("conversionRate", 0.85);
        funnel.add(negotiation);
        
        Map<String, Object> closed = new HashMap<>();
        closed.put("stage", "成交");
        closed.put("count", 195);
        closed.put("value", 975000);
        closed.put("conversionRate", 1.0);
        funnel.add(closed);
        
        data.put("funnel", funnel);
        
        // 销售趋势
        List<Map<String, Object>> trend = new ArrayList<>();
        String[] months = {"一月", "二月", "三月", "四月", "五月", "六月"};
        Random random = new Random();
        for (String month : months) {
            Map<String, Object> item = new HashMap<>();
            item.put("period", month);
            item.put("revenue", 150000 + random.nextInt(100000));
            item.put("deals", 30 + random.nextInt(20));
            item.put("average", 4000 + random.nextInt(2000));
            trend.add(item);
        }
        data.put("trend", trend);
        
        // 销售团队绩效
        List<Map<String, Object>> teamPerformance = new ArrayList<>();
        String[] teams = {"团队A", "团队B", "团队C", "团队D"};
        for (String team : teams) {
            Map<String, Object> item = new HashMap<>();
            item.put("team", team);
            item.put("revenue", 200000 + random.nextInt(300000));
            item.put("deals", 40 + random.nextInt(35));
            item.put("hitRate", 0.3 + (random.nextDouble() * 0.4));
            item.put("cycleTime", 20 + random.nextInt(30));
            teamPerformance.add(item);
        }
        data.put("teamPerformance", teamPerformance);
        
        return Result.success(data);
    }
    
    /**
     * 获取服务分析数据
     */
    @GetMapping("/service")
    public Result<Map<String, Object>> serviceAnalytics(
            @RequestParam(required = false) String timeRange,
            @RequestParam(required = false) String category,
            @RequestParam(required = false) String dimension) {
        
        // 此处为模拟数据
        Map<String, Object> data = new HashMap<>();
        
        // 服务请求统计
        Map<String, Integer> requestStats = new HashMap<>();
        requestStats.put("total", 850);
        requestStats.put("open", 120);
        requestStats.put("inProgress", 230);
        requestStats.put("resolved", 500);
        data.put("requestStats", requestStats);
        
        // 平均响应和解决时间
        Map<String, Object> timeMetrics = new HashMap<>();
        timeMetrics.put("responseTime", 4.2); // 小时
        timeMetrics.put("resolutionTime", 28.5); // 小时
        timeMetrics.put("firstContactResolution", 0.62); // 比率
        data.put("timeMetrics", timeMetrics);
        
        // 客户满意度
        Map<String, Object> satisfaction = new HashMap<>();
        satisfaction.put("average", 4.3); // 5分制
        satisfaction.put("promoters", 0.65);
        satisfaction.put("passives", 0.25);
        satisfaction.put("detractors", 0.10);
        satisfaction.put("nps", 55); // NPS得分
        data.put("satisfaction", satisfaction);
        
        // 问题类别分布
        Map<String, Integer> categories = new HashMap<>();
        categories.put("技术支持", 340);
        categories.put("账户问题", 210);
        categories.put("产品咨询", 150);
        categories.put("账单问题", 80);
        categories.put("其他", 70);
        data.put("categories", categories);
        
        return Result.success(data);
    }
    
    /**
     * 获取预测分析数据
     */
    @GetMapping("/prediction")
    public Result<Map<String, Object>> predictionAnalytics(
            @RequestParam String modelType,
            @RequestParam Map<String, Object> parameters) {
        
        // 此处为模拟数据
        Map<String, Object> data = new HashMap<>();
        
        // 根据模型类型返回不同的预测结果
        switch(modelType) {
            case "churn":
                // 客户流失预测
                List<Map<String, Object>> churnPredictions = generateChurnPredictions();
                data.put("predictions", churnPredictions);
                data.put("accuracy", 0.86);
                data.put("precision", 0.82);
                data.put("recall", 0.79);
                break;
                
            case "lifetime_value":
                // 客户生命周期价值预测
                List<Map<String, Object>> ltvPredictions = generateLTVPredictions();
                data.put("predictions", ltvPredictions);
                data.put("accuracy", 0.83);
                data.put("mse", 1250.4);
                data.put("r2", 0.76);
                break;
                
            case "sales_forecast":
                // 销售预测
                List<Map<String, Object>> salesForecast = generateSalesForecast();
                data.put("forecast", salesForecast);
                data.put("accuracy", 0.89);
                data.put("mape", 8.4); // 平均百分比误差
                break;
                
            default:
                return Result.error("未知的预测模型类型");
        }
        
        return Result.success(data);
    }
    
    /**
     * 生成模拟的客户流失预测数据
     */
    private List<Map<String, Object>> generateChurnPredictions() {
        List<Map<String, Object>> predictions = new ArrayList<>();
        Random random = new Random();
        String[] names = {"客户A", "客户B", "客户C", "客户D", "客户E", "客户F", "客户G", "客户H", "客户I", "客户J"};
        
        for (String name : names) {
            Map<String, Object> prediction = new HashMap<>();
            prediction.put("customerId", random.nextInt(10000));
            prediction.put("name", name);
            double churnProbability = 0.1 + (random.nextDouble() * 0.8);
            prediction.put("churnProbability", Math.round(churnProbability * 100) / 100.0);
            prediction.put("risk", churnProbability > 0.7 ? "高" : (churnProbability > 0.3 ? "中" : "低"));
            prediction.put("lastActivity", random.nextInt(90) + " 天前");
            prediction.put("contractEnd", random.nextInt(180) + " 天后");
            predictions.add(prediction);
        }
        
        return predictions;
    }
    
    /**
     * 生成模拟的客户生命周期价值预测数据
     */
    private List<Map<String, Object>> generateLTVPredictions() {
        List<Map<String, Object>> predictions = new ArrayList<>();
        Random random = new Random();
        String[] names = {"客户K", "客户L", "客户M", "客户N", "客户O", "客户P", "客户Q", "客户R", "客户S", "客户T"};
        
        for (String name : names) {
            Map<String, Object> prediction = new HashMap<>();
            prediction.put("customerId", random.nextInt(10000));
            prediction.put("name", name);
            double ltv = 5000 + (random.nextDouble() * 45000);
            prediction.put("predictedLTV", Math.round(ltv * 100) / 100.0);
            prediction.put("confidence", Math.round((0.6 + random.nextDouble() * 0.35) * 100) / 100.0);
            prediction.put("segment", ltv > 30000 ? "高价值" : (ltv > 15000 ? "中等价值" : "低价值"));
            prediction.put("tenure", random.nextInt(36) + " 个月");
            predictions.add(prediction);
        }
        
        return predictions;
    }
    
    /**
     * 生成模拟的销售预测数据
     */
    private List<Map<String, Object>> generateSalesForecast() {
        List<Map<String, Object>> forecast = new ArrayList<>();
        Random random = new Random();
        String[] periods = {"7月", "8月", "9月", "10月", "11月", "12月"};
        
        double lastValue = 100000 + (random.nextDouble() * 50000);
        for (String period : periods) {
            Map<String, Object> prediction = new HashMap<>();
            prediction.put("period", period);
            
            // 使前后数据有一定相关性
            double change = 0.8 + (random.nextDouble() * 0.4);
            if (random.nextBoolean()) {
                lastValue = lastValue * change;
            } else {
                lastValue = lastValue / change;
            }
            
            prediction.put("predictedRevenue", Math.round(lastValue * 100) / 100.0);
            prediction.put("lowerBound", Math.round(lastValue * 0.8 * 100) / 100.0);
            prediction.put("upperBound", Math.round(lastValue * 1.2 * 100) / 100.0);
            prediction.put("growthRate", Math.round((change - 1) * 100) / 100.0);
            forecast.add(prediction);
        }
        
        return forecast;
    }
    
    /**
     * 创建新的分析模型
     */
    @PostMapping("/models")
    public Result<Map<String, Object>> createModel(@RequestBody Map<String, Object> modelData) {
        // 此处应调用服务层创建模型
        // 返回模拟数据
        Map<String, Object> result = new HashMap<>();
        result.put("modelId", new Random().nextInt(1000));
        result.put("created", true);
        result.put("status", "initializing");
        
        return Result.success(result);
    }
    
    /**
     * 获取已有分析模型列表
     */
    @GetMapping("/models")
    public Result<List<Map<String, Object>>> listModels() {
        // 返回模拟数据
        List<Map<String, Object>> models = new ArrayList<>();
        Random random = new Random();
        
        for (int i = 1; i <= 5; i++) {
            Map<String, Object> model = new HashMap<>();
            model.put("id", i);
            
            String[] types = {"客户流失预测", "客户价值预测", "销售预测", "客户分群", "产品推荐"};
            model.put("name", types[i-1] + "模型");
            model.put("type", types[i-1]);
            model.put("createdAt", "2023-0" + (i+1) + "-" + (10+i));
            model.put("accuracy", 0.7 + (random.nextDouble() * 0.25));
            model.put("status", i < 4 ? "active" : (i == 4 ? "training" : "error"));
            model.put("lastRun", i < 4 ? "2023-0" + (i+2) + "-" + (5+i) : null);
            
            models.add(model);
        }
        
        return Result.success(models);
    }
    
    /**
     * 获取分析模型详情
     */
    @GetMapping("/models/{id}")
    public Result<Map<String, Object>> getModelDetail(@PathVariable Integer id) {
        // 返回模拟数据
        Map<String, Object> model = new HashMap<>();
        Random random = new Random();
        
        model.put("id", id);
        
        String[] types = {"客户流失预测", "客户价值预测", "销售预测", "客户分群", "产品推荐"};
        int typeIndex = (id - 1) % types.length;
        model.put("name", types[typeIndex] + "模型");
        model.put("type", types[typeIndex]);
        model.put("description", "用于" + types[typeIndex] + "的机器学习模型");
        model.put("createdAt", "2023-0" + (typeIndex+1) + "-" + (10+typeIndex));
        model.put("createdBy", "管理员");
        model.put("status", id < 4 ? "active" : (id == 4 ? "training" : "error"));
        
        // 性能指标
        Map<String, Object> performance = new HashMap<>();
        performance.put("accuracy", 0.7 + (random.nextDouble() * 0.25));
        performance.put("precision", 0.65 + (random.nextDouble() * 0.3));
        performance.put("recall", 0.6 + (random.nextDouble() * 0.35));
        performance.put("f1", 0.68 + (random.nextDouble() * 0.27));
        model.put("performance", performance);
        
        // 特征重要性
        List<Map<String, Object>> features = new ArrayList<>();
        String[][] featureNames = {
            {"账户年龄", "产品使用频率", "客户服务互动", "账单金额", "支付延迟"},
            {"购买频率", "平均订单价值", "客户年龄", "产品类别", "互动评分"},
            {"历史销售", "季节性指标", "促销活动", "市场趋势", "竞争活动"}
        };
        
        String[] currentFeatures = featureNames[Math.min(typeIndex, 2)];
        double total = 0;
        double[] importances = new double[currentFeatures.length];
        
        for (int i = 0; i < currentFeatures.length; i++) {
            double value = 0.1 + random.nextDouble() * 0.5;
            importances[i] = value;
            total += value;
        }
        
        for (int i = 0; i < currentFeatures.length; i++) {
            Map<String, Object> feature = new HashMap<>();
            feature.put("name", currentFeatures[i]);
            feature.put("importance", importances[i] / total);
            features.add(feature);
        }
        
        model.put("features", features);
        
        // 最近运行历史
        List<Map<String, Object>> history = new ArrayList<>();
        for (int i = 1; i <= 3; i++) {
            Map<String, Object> run = new HashMap<>();
            run.put("runId", id * 100 + i);
            run.put("date", "2023-" + (10-i) + "-" + (20-i));
            run.put("duration", 120 + random.nextInt(300));
            run.put("accuracy", 0.7 + (random.nextDouble() * 0.25));
            run.put("status", "completed");
            history.add(run);
        }
        
        model.put("runHistory", history);
        
        return Result.success(model);
    }
} 